package com.orbitdevs.testgame.map;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.tiled.SimpleTileAtlas;
import com.badlogic.gdx.graphics.g2d.tiled.TileMapRenderer;
import com.badlogic.gdx.graphics.g2d.tiled.TiledLoader;
import com.badlogic.gdx.graphics.g2d.tiled.TiledMap;
import com.badlogic.gdx.graphics.g2d.tiled.TiledLayer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Array;
import com.orbitdevs.testgame.graphics.BaseSprite;

public class Map {
	public TiledMap map;
	public SimpleTileAtlas atlas;
	public TileMapRenderer renderer;
	public TiledLayer colLayer;

	public int MAPWIDTH, MAPHEIGHT;
	float TILEWIDTH, TILEHEIGHT;

	public Map(float tw, float th) {
		this.TILEWIDTH = tw;
		this.TILEHEIGHT = th;

		map = TiledLoader.createMap(Gdx.files.internal("data/Maps/platformtest.tmx"));

		atlas = new SimpleTileAtlas(map, Gdx.files.internal("data/Maps/"));
		renderer = new TileMapRenderer(map, atlas, 32, 32, TILEWIDTH, TILEHEIGHT);
		colLayer = map.layers.get(0);

		this.MAPWIDTH = renderer.getMapWidthUnits();
		this.MAPHEIGHT = renderer.getMapHeightUnits();
	}

	public float[] getTilePos(float[] pos) {
		return new float[] { (float) (Math.floor(pos[0]) / TILEWIDTH), (float) (Math.floor(pos[1] / TILEHEIGHT)) };
	}

	public int getTileId(float[] pos) {
		int y = (int) Math.floor((float)MAPHEIGHT / TILEHEIGHT) - (int) Math.floor(pos[1] / TILEHEIGHT);
		int x = (int) Math.floor(pos[0] / TILEWIDTH);
		return map.layers.get(0).tiles[y][x];
	}

	public int[][] getPointIDs(Map map, BaseSprite spr, float dt) {
		int[] IDs = new int[6];
		int[] cIDs = new int[6];

		IDs[0] = getTileId(spr.getBLeft(dt)); 
		IDs[1] = getTileId(spr.getTLeft(dt)); 
		IDs[2] = getTileId(spr.getMTop(dt));
		IDs[3] = getTileId(spr.getTRight(dt));
		IDs[4] = getTileId(spr.getBRight(dt));
		IDs[5] = getTileId(spr.getMBot(dt));
		
		cIDs[0] = getTileId(spr.colGetBLeft(dt)); 		
		cIDs[1] = getTileId(spr.colGetTLeft(dt)); 
		cIDs[2] = getTileId(spr.colGetMTop(dt));
		cIDs[3] = getTileId(spr.colGetTRight(dt));
		cIDs[4] = getTileId(spr.colGetBRight(dt));
		cIDs[5] = getTileId(spr.colGetMBot(dt));

		return new int[][] {IDs, cIDs};
	}

	public float getTileRight(float[] pos) {
		float[] tilePos = getTilePos(pos);
		return (tilePos[0]) * TILEWIDTH;

	}

	public float getTileLeft(float[] pos) {
		float[] tilePos = getTilePos(pos);
		return (tilePos[0]) * TILEWIDTH;

	}

	public float getTileTop(float[] pos) {
		float[] tilePos = getTilePos(pos);
		return ((tilePos[1] + 1) * TILEHEIGHT);
	}

	public float getTileBottom(float[] pos) {
		float[] tilePos = getTilePos(pos);
		return ((tilePos[1]) * TILEHEIGHT);
	}

}
